package com.quyunshuo.module.home.manager

import android.os.Handler
import android.os.Looper
import android.util.Log
import java.util.*

class TimeManager {
    private var currentRunnable: Runnable? = null
    private var currentHandler: Handler? = null

    fun getMinutesUntilTarget(hour: Int, minute: Int): Long {
        val target = getTargetDateTime(hour, minute)
        val now = Calendar.getInstance()

        // 计算毫秒差值
        val millisUntilTarget = target.timeInMillis - now.timeInMillis

        // 转换为分钟（向上取整，确保至少1分钟）
        return maxOf(1, millisUntilTarget / (1000 * 60))
    }

    // 1. 比较时间并判断是今天还是明天
    fun getTargetDateTime(hour: Int, minute: Int): Calendar {
        val now = Calendar.getInstance()
        val target = Calendar.getInstance()

        // 设置目标时间（默认今天）
        target.set(Calendar.HOUR_OF_DAY, hour)
        target.set(Calendar.MINUTE, minute)
        target.set(Calendar.SECOND, 0)
        target.set(Calendar.MILLISECOND, 0)

        // 如果目标时间已过，则设置为明天
        if (target.before(now)) {
            target.add(Calendar.DAY_OF_YEAR, 1)
        }

        return target
    }

    // 2. 每秒对比时间，到达指定时间后响应
    fun startTimeComparison(hour: Int, minute: Int, callback: (reached: Boolean) -> Unit) {
        // 先取消之前的计时任务
        cancelTimeComparison()

        val target = getTargetDateTime(hour, minute)
        val handler = Handler(Looper.getMainLooper())

        val runnable = object : Runnable {
            override fun run() {
                val now = Calendar.getInstance()
                Log.d("TimeManager", "当前时间: ${now.time}")
                Log.d("TimeManager", "目标时间: ${target.time}")

                if (now >= target) {
                    // 目标时间到达
                    callback(true)
                    // 任务完成，清除引用
                    currentRunnable = null
                    currentHandler = null
                } else {
                    // 未到达目标时间，继续检查
                    callback(false)
                    handler.postDelayed(this, 1000) // 每秒钟检查一次
                }
            }
        }

        // 保存当前任务引用
        currentRunnable = runnable
        currentHandler = handler

        // 开始首次检查
        handler.post(runnable)
    }

    // 取消当前的计时任务
    fun cancelTimeComparison() {
        currentRunnable?.let { runnable ->
            currentHandler?.removeCallbacks(runnable)
            currentHandler = null
            currentRunnable = null
            Log.d("TimeManager", "已取消计时任务")
        }
    }

    // 检查是否有正在运行的计时任务
    fun isComparisonRunning(): Boolean {
        return currentRunnable != null
    }
}